package com.briup.jz.service.impl;

import com.briup.jz.bean.Article;
import com.briup.jz.bean.ArticleExample;
import com.briup.jz.bean.Category;
import com.briup.jz.bean.extend.ArticleExtend;
import com.briup.jz.dao.ArticleMapper;
import com.briup.jz.dao.extend.ArticleExtendMapper;
import com.briup.jz.service.IArticleService;
import com.briup.jz.utils.CustomerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleExtendMapper articleExtendMapper;


    @Override
    public void saveOrUpdate(Article article) throws CustomerException {
        if (article.getId()!=null){
            articleMapper.updateByPrimaryKey(article);
        }else{
            articleMapper.insert(article);
        }
    }
 
    @Override
    public List<Article> query(Article article) {
        ArticleExample example = new ArticleExample();
        ArticleExample.Criteria criteria = example.createCriteria();
        if (article.getStatus()!=null){
            criteria.andStatusEqualTo(article.getStatus());
        }
        if (article.getCategoryId()!=null){
            criteria.andCategoryIdEqualTo(article.getCategoryId());
        }
        if (article.getTitle()!=null) {
            criteria.andTitleLike("%" + article.getTitle() + "%");
        }
        return articleMapper.selectByExample(example);
    } 

    @Override
    public ArticleExtend read(long id) {
        return articleExtendMapper.selectById(id);
    }

    @Override
    public List<ArticleExtend> queryCascade(String status, String title, Long categoryId) {
        return articleExtendMapper.select(status,title,categoryId);
    }

    @Override
    public Article queryArticleById(long id) throws CustomerException{
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null){
            throw new CustomerException("要查询的文章不存在");
        }
        return article;
    }

    @Override
    public void deleteById(long id) throws CustomerException {
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null) {
            throw new CustomerException("要删除的文章不存在");
        }
        articleMapper.deleteByPrimaryKey(id);
    }
}
